package com.ebeitech.camera;

import java.io.File;
import java.io.IOException;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.TextView;

import com.ebeitech.doorapp.R;
import com.ebeitech.doorapp.util.PublicUtil;
import com.ebeitech.doorapp.view.OnInitializeListener;
import com.ebeitech.library.constant.SPConstants;
import com.ebeitech.library.util.TimeUtil;

public class MediaRecorderFragment extends Fragment {

	private Context mContext;
	private ImageView button_exit;
	private ImageView button_start;
	private View use;
	private MediaRecorder recorder;
	private Chronometer timer;
	private TextView mStatusText;
	
	private String path;
	private boolean isStart = false;
	private boolean isRecorded = false;
	private boolean isGranted = true;
	
	private OnInitializeListener mInitializeListener;
	
	public void setOnInitializeListener(OnInitializeListener l) {
		mInitializeListener = l;
	}


	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.ebei_activity_media_mediarecorder, null);
		init(view);
		
		if (!PublicUtil.checkSelfPermission(mContext, Manifest.permission.RECORD_AUDIO)) {
			isGranted = false;
			PublicUtil.requestPermissions(this, Manifest.permission.RECORD_AUDIO, 1);
		}
		return view;
	}
	
	//@Override
	public void onRequestPermissionsResult(int requestCode,
			String[] permissions, int[] grantResults) {
		// TODO Auto-generated method stub
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		isGranted = true;
		for (int i = 0; i < grantResults.length; i++) {
			if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
				isGranted = false;
			}
		}
		if (!isGranted) {
			((Activity) mContext).finish();
		}
	}

	private void init(View view) {
		mContext = getActivity();
		if (mInitializeListener != null) {
			mInitializeListener.onFinished();
		}
		
		button_start = (ImageView) view.findViewById(R.id.start);
		button_exit = (ImageView) view.findViewById(R.id.exit);
		timer = (Chronometer) view.findViewById(R.id.recodertext);
		mStatusText = (TextView) view.findViewById(R.id.textView1);
		
		button_start.setImageResource(R.drawable.ebei_voice_start_before);
		button_start.setOnClickListener(new AudioListerner());
		mStatusText.setVisibility(View.GONE);
		button_exit.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				if (isRecorded &&
						!mContext.getString(R.string.ebei_recording_doing).equals(mStatusText.getText().toString())) {
					// 取消返回录音首页面
					isRecorded = false;
					use.setVisibility(View.GONE);
					button_start.setImageResource(R.drawable.ebei_voice_start_before);
					button_exit.setImageResource(R.drawable.ebei_camera_exit_selector);
					mStatusText.setText(R.string.ebei_recording_end);
					mStatusText.setVisibility(View.GONE);
					timer.setBase(SystemClock.elapsedRealtime());
					File file = new File(path);
					file.delete();
				} else {
					// 退出应用程序
					finish();
				}
			}
		});
		use = view.findViewById(R.id.use);
		use.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				button_start.setEnabled(false);
				button_exit.setEnabled(false);
				use.setVisibility(View.GONE);
				Intent i = new Intent();
				Bundle b = new Bundle();
				b.putString("mediapath", path);
				i.putExtras(b);
				i.putExtra(SPConstants.FILE_TYPE, SPConstants.REQUEST_VOICE);
				((Activity) mContext).setResult(Activity.RESULT_OK, i);
				finish();
			}
		});
		use.setVisibility(View.GONE);
		view.findViewById(R.id.view_use).setVisibility(View.VISIBLE);
		view.findViewById(R.id.use_count).setVisibility(View.INVISIBLE);
	}

	class AudioListerner implements OnClickListener {

		public void onClick(View v) {
			if (v == button_start) {
				if (!isRecorded) {
					isRecorded = true;
					mStatusText.setText(R.string.ebei_recording_doing);
					mStatusText.setVisibility(View.VISIBLE);
					button_start.setImageResource(R.drawable.ebei_voice_start_doing);
					timer.setBase(SystemClock.elapsedRealtime());
					timer.start();
					initializeAudio();
				} else {
					if (recorder != null && isStart) {
						if (recorder != null) {
							recorder.stop();
							recorder.release();
							isStart = false;
						}
					}
					use.setVisibility(View.VISIBLE);
					button_exit.setImageResource(R.drawable.ebei_camera_delete_selector);
					button_start.setImageResource(R.drawable.ebei_voice_start_after);
					mStatusText.setText(R.string.ebei_recording_end);
					
					timer.stop();
				}
			}
		}

		@SuppressWarnings("deprecation")
		private void initializeAudio() {
			recorder = new MediaRecorder();
			recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
			recorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
			recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
			String fileName = TimeUtil.getCurrentTime("yyyyMMdd_HHmmss");
			path = PublicUtil.getAppFile(mContext) + "/" + fileName + ".amr";
			recorder.setOutputFile(path);
			try {
				recorder.prepare();
				recorder.start();
				isStart = true;
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public void finish() {
		((Activity) mContext).finish();
		if (recorder != null && isStart) {
			recorder.stop();
			recorder.release();
			isStart = false;
		}
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_HOME:
			return true;
		case KeyEvent.KEYCODE_CALL:
			return true;
		case KeyEvent.KEYCODE_SYM:
			return true;
		case KeyEvent.KEYCODE_STAR:
			return true;
		case KeyEvent.KEYCODE_BACK:
			button_exit.performClick();
			return true;
		}
		return ((Activity) mContext).onKeyDown(keyCode, event);
	}
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (recorder != null && isStart) {
			recorder.stop();
			recorder.release();
			isStart = false;
		}
	}


}
